﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
using System.IO;
using System.Xml;
using SqlMiM.Common;
using System.ComponentModel;
using System.Collections.ObjectModel;
using SqlMiM.ViewModel;

namespace SqlMiM
{
    public class PluginContext : INotifyPropertyChanged
    {

        private static PluginContext current;
        private PluginViewModel activePlugin;
        private ObservableCollection<PluginViewModel> currentPlugins;

        public static PluginContext Current
        {
            get
            {
                if (current == null)
                {
                    current = new PluginContext();
                }

                return current;
            }
        }


        private PluginContext()
        {
            currentPlugins = new ObservableCollection<PluginViewModel>();
        }

        /// <summary>
        /// Get List of plugins actually loaded in tab control
        /// May have distinct plugins or not
        /// </summary>
        public ObservableCollection<PluginViewModel> CurrentPlugins
        {
            get { return currentPlugins; }
            set
            {
                currentPlugins = value;
                this.RaisePropertyChanged("CurrentPlugins");
            }
        }

        /// <summary>
        /// Get current selected tab control plugin
        /// may be null
        /// </summary>
        public PluginViewModel ActivePlugin
        {
            get { return activePlugin; }
            set
            {
                activePlugin = value;
                this.RaisePropertyChanged("ActivePlugin");
            }
        }


        internal void AddPlugin(PluginViewModel pluginModel)
        {
            var pluginExist = (from p in this.CurrentPlugins
                               where p.Plugin.Name.Equals(pluginModel.Plugin.Name, StringComparison.InvariantCultureIgnoreCase)
                               select p).Any();

            if (!pluginExist)
                this.CurrentPlugins.Add(pluginModel);

            this.ActivePlugin = pluginModel;

        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Raises this object's PropertyChanged event.
        /// </summary>
        /// <param name="propertyName">The property that has a new value.</param>
        protected virtual void RaisePropertyChanged(string propertyName)
        {

            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
            {
                var e = new PropertyChangedEventArgs(propertyName);
                handler(this, e);
            }
        }

        #endregion

    
    }
}
